package com.nnfe.fyd.utils;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.nnfe.fyd.R;

import java.lang.ref.WeakReference;
import java.util.ArrayList;


/**
 * 应用程序UI工具包：封装UI相关的一些操作
 */
public class DialogUtil {


    /**
     * 全局web样式
     */
    public final static String WEB_STYLE = "<style>* {font-size:16px;line-height:20px;} p {color:#333;} a {color:#3E62A6;} img {max-width:310px;} "
            + "img.alignleft {float:left;max-width:120px;margin:0 10px 5px 0;border:1px solid #ccc;background:#fff;padding:2px;} "
            + "pre {font-size:9pt;line-height:12pt;font-family:Courier New,Arial;border:1px solid #ddd;border-left:5px solid #6CE26C;background:#f6f6f6;padding:5px;} "
            + "a.tag {font-size:15px;text-decoration:none;background-color:#bbd6f3;border-bottom:2px solid #3E6D8E;border-right:2px solid #7F9FB6;color:#284a7b;margin:2px 2px 2px 0;padding:2px 4px;white-space:nowrap;}</style>";

    /**
     * 加载中对话框
     */
    public static ProgressDialog mLoadingDialog;

    /**
     * 普通对话框 builder
     */
    public static AlertDialog.Builder builder;

    /**
     *  普通对话框 alertDialog
     */
    public static Dialog alertDialog;

    /**
     * 初始化普通对话框 调用之后可自定义设置其他属性 调用create()来创建 调用show()直接显示
     *
     * @param title         标题
     * @param message       内容
     * @param textLeft      左边按钮的文字
     * @param leftListener  左边按钮监听
     * @param textRight     右边按钮的文字
     * @param rightListener 右边按钮的监听
     */
    public static AlertDialog.Builder initAlertDialog(Context context, String title, String message,
                                                      String textLeft, DialogInterface.OnClickListener leftListener,
                                                      String textRight, DialogInterface.OnClickListener rightListener) {
        try {
            builder = null;
            builder = new AlertDialog.Builder(context, R.style.DatePickerDialog);
            if (!TextUtils.isEmpty(title)) {
                builder.setTitle(title);
            }
            if (!TextUtils.isEmpty(message)) {
                builder.setMessage(message);
            }
            if (!TextUtils.isEmpty(textLeft)) {
                builder.setPositiveButton(textLeft, leftListener);
            }
            if (!TextUtils.isEmpty(textRight)) {
                builder.setNegativeButton(textRight, rightListener);
            }
            return builder;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param titleId       标题ID
     * @param messageId     内容
     * @param textLeftId    左边按钮的文字ID
     * @param leftListener  左边按钮监听
     * @param textRightId   右边按钮的文字ID
     * @param rightListener 右边按钮的监听
     */
    public static AlertDialog.Builder initAlertDialog(Context context, int titleId, int messageId,
                                                      int textLeftId, DialogInterface.OnClickListener leftListener,
                                                      int textRightId, DialogInterface.OnClickListener rightListener) {
        builder = initAlertDialog(context, titleId == 0 ? "" : context.getString(titleId),
                messageId == 0 ? "" : context.getString(messageId),
                textLeftId == 0 ? "" : context.getString(textLeftId), leftListener,
                textRightId == 0 ? "" : context.getString(textRightId), rightListener);
        return builder;
    }

    public static AlertDialog.Builder initAlertDialog(Context context, String title,
                                                      String[] items, DialogInterface.OnClickListener listener) {
        try {
            builder = initAlertDialog(context, title, "", "", null, "", null);
            builder.setItems(items, listener);
            return builder;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 显示普通对话框
     *
     * @param context
     * @param title
     * @param items
     * @param listener
     */
    public static void showAlertDialog(Context context, String title,
                                       String[] items, DialogInterface.OnClickListener listener) {
        try {
            builder = initAlertDialog(context, title, items, listener);
            builder.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示列表对话框
     *
     * @param context
     * @param title
     * @param data
     * @param listener
     */
    public static void showListDialog(Context context, String title,
                                      ArrayList<String> data, DialogInterface.OnClickListener listener) {

        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(context, R.layout.dialog_list_simple_item, data);
        AlertDialog dialog = new AlertDialog.Builder(context,R.style.DatePickerDialog)
                .setTitle(title)
                .setAdapter(stringArrayAdapter, listener)
                .create();
        dialog.show();
    }

    /**
     * 点击空白区域消失的对话框
     *
     * @param context
     * @param title
     * @param items
     * @param listener
     */
    public static void showEnableCancleAlertDialog(Context context, String title, String[] items,
                                                   DialogInterface.OnClickListener listener) {
        try {
            builder = initAlertDialog(context, title, items, listener);
            Dialog dialog = builder.show();
            dialog.setCanceledOnTouchOutside(true);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     *
     * @param context           // 上下文
     * @param title             // 头信息
     * @param message           // 内容
     * @param textLeft          // 左按钮显示内容
     * @param leftListener      // 左按钮点击事件
     * @param textRight         // 右按钮显示内容
     * @param rightListener     // 右按钮点击事件
     */
    public static void showAlertDialog(Context context, String title, String message, String textLeft,
                                       DialogInterface.OnClickListener leftListener, String textRight,
                                       DialogInterface.OnClickListener rightListener) {
        try {
            builder = initAlertDialog(context, title, message, textLeft, leftListener, textRight, rightListener);
            builder.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示加载中的对话框
     *
     * @param message 提示信息
     */
    public static void showLoadingDialog(Context context, String message) {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new ProgressDialog(context,R.style.CoustomDialog);
            }
            mLoadingDialog.setMessage(message);
            mLoadingDialog.setCancelable(true);
            if (!mLoadingDialog.isShowing() && !((Activity) context).isFinishing()) {
                try {
                    mLoadingDialog.show();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示加载中的对话框
     *
     * @param message 提示信息
     */
    public static void showLoadingDialog(Context context, String message, boolean cancelable) {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new ProgressDialog(context);
            }
            mLoadingDialog.setMessage(message);
            mLoadingDialog.setCancelable(cancelable);
            if (!mLoadingDialog.isShowing() && !((Activity) context).isFinishing()) {
                try {
                    mLoadingDialog.show();
                } catch (Throwable e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示加载中对话框
     */
    public static void showLoadingDialog(Context context) {
        showLoadingDialog(context, "加载中");
    }

    /**
     * 关闭加载中的对话框
     */
    public static void dismissLoadingDialog(Context context) {
        try {
            // if (mLoadingDialog != null && !((Activity)
            // context).isFinishing()) {
            if (mLoadingDialog != null) {
                mLoadingDialog.dismiss();
                mLoadingDialog = null;
            }
            // }
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除全部对话框
     */
    public static void delDialog(Context context) {
        dismissLoadingDialog(context);
        if (mLoadingDialog != null) {
            mLoadingDialog = null;
        }

    }

    /**
     * 底部dialog
     *
     * @param context
     * @param title
     * @param items
     * @param listener
     */
    public static void getBottomDialog(Context context, String title, String[] items,
                                       DialogInterface.OnClickListener listener) {

        builder = new AlertDialog.Builder(context);

        TextView title_tv = new TextView(context);
        title_tv.setTextColor(context.getResources().getColor(R.color.gray));
        title_tv.setTextSize(15);
        title_tv.setText(title);
        title_tv.setPadding(0, 20, 0, 20);
        title_tv.setGravity(Gravity.CENTER);
        builder.setCustomTitle(title_tv);

        ListAdapter itemlist = new ArrayAdapter(context, R.layout.dialog_list_item, items);
        builder.setAdapter(itemlist, listener);
        Dialog dialog = builder.create();
        Window window = dialog.getWindow();
        window.setGravity(Gravity.BOTTOM);
        dialog.setCanceledOnTouchOutside(true);
        dialog.show();
    }

    /**
     * 显示自定义alertdialog
     *
     * @param context  // 上下文
     * @param resource // 自定义布局
     * @param ids      // 自定义布局的 组件 id
     * @param listener // 自定义的 listener
     */
    public static void showCustomAlert(Context context, int resource, int[] ids, OnClickListener listener) {
        try {
            final View cotentView = View.inflate(context, resource, null);
            final AlertDialog dialog = new AlertDialog.Builder(context,R.style.CoustomDialog).setView(cotentView).create();
            listener.setDialog(dialog);
            for (int id : ids) {
                cotentView.findViewById(id).setOnClickListener(listener);
            }
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示自定义alertdialog
     *
     * @param context   // 上下文
     * @param view      // 自定义布局
     * @param ids       // 自定义布局的 组件 id
     * @param listener  // 自定义的 listener
     */
    public static void showCustomAlert(Context context, View view, int[] ids, OnClickListener listener) {
        try {
            final AlertDialog dialog = new AlertDialog.Builder(context,R.style.CoustomDialog).setView(view).create();
            listener.setDialog(dialog);
            for (int id : ids) {
                view.findViewById(id).setOnClickListener(listener);
            }
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 显示自定义alertdialog
     *
     * @param context   // 上下文
     * @param view      // 自定义布局
     * @param ids       // 自定义布局的 组件 id
     * @param listener  // 自定义的 listener
     */
    public static void showCustomAlert(Context context, View view, WindowManager.LayoutParams a, int[] ids, OnClickListener listener) {
        try {
            final AlertDialog dialog = new AlertDialog.Builder(context,R.style.share_dialog).setView(view).create();
            dialog.getWindow().setAttributes(a);
            listener.setDialog(dialog);
            for (int id : ids) {
                view.findViewById(id).setOnClickListener(listener);
            }
            dialog.show();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 拨打电话,联系客服的 dialog
     * @param mContext
     * @param phone_num
     */
    public static void showCallDialog(final Activity mContext, final String phone_num) {

        if (alertDialog == null) {
            View view = View.inflate(mContext,R.layout.dialog_call,null);
            alertDialog = new Dialog(mContext, R.style.transparentFrameWindowStyle);
            alertDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
            Window window = alertDialog.getWindow();
            // 设置显示动画
            window.setWindowAnimations(R.style.main_menu_animstyle);
            WindowManager.LayoutParams wl = window.getAttributes();
            wl.x = 0;
            wl.y = mContext.getWindowManager().getDefaultDisplay().getHeight();
            // 以下这两句是为了保证按钮可以水平满屏
            wl.width = ViewGroup.LayoutParams.MATCH_PARENT;
            wl.height = ViewGroup.LayoutParams.WRAP_CONTENT;
            // 设置显示位置
            alertDialog.onWindowAttributesChanged(wl);
            // 设置点击外围解散
            alertDialog.setCanceledOnTouchOutside(true);
            alertDialog.show();
            Button btn_call = (Button) view.findViewById(R.id.btn_call);
            btn_call.setText(phone_num);
            Button btn_cancle = (Button) view.findViewById(R.id.btn_cancle);
            btn_call.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (phone_num != null && !phone_num.equals("")) {
                        Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + phone_num));
                        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        if (ActivityCompat.checkSelfPermission(mContext, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
                            // TODO: Consider calling
                            //    ActivityCompat#requestPermissions
                            // here to request the missing permissions, and then overriding
                            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
                            //                                          int[] grantResults)
                            // to handle the case where the user grants the permission. See the documentation
                            // for ActivityCompat#requestPermissions for more details.
                            Toast.makeText(mContext,"请同意用户电话权限", Toast.LENGTH_LONG).show();
                            return;
                        }
                        mContext.startActivity(intent);
                        alertDialog.dismiss();
                    }
                }
            });
            btn_cancle.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    alertDialog.dismiss();
                }
            });
        } else if (!alertDialog.isShowing()) {
            //btn_call.setText(phone_num);
            alertDialog.show();
        }
    }


    public static abstract class OnClickListener implements View.OnClickListener {
        private WeakReference<DialogInterface> mDialog;

        @Override
        public void onClick(View v) {
            if (mDialog != null && mDialog.get() != null) {
                onClick(mDialog.get(), v);
            } else {
            }
        }

        public abstract void onClick(DialogInterface dialog, View view);

        void setDialog(DialogInterface dialog) {
            this.mDialog = new WeakReference<DialogInterface>(dialog);
        }
    }
}
